package com.br.egaragens.Requisicao;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.br.egaragens.entidades.Usuario;
import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;

/**
 * Created by DIVINO on 23/10/2014.
 */
public class Requisicao extends AsyncTask<String,Void,String> {

    private Context ctx;
    final static String serviceURL = "http://192.168.1.20/wcf/Service1.svc/";

    public Requisicao(Context ctx){
        this.ctx = ctx;
    }


    public Usuario getUsuario(String s) {

        try {

        //cria a requisicao get
        HttpGet request = new HttpGet(serviceURL+"GetUsuario/"+s);
        //indica que o pacote será em formato json
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //envia a requisicao ao servidor
        HttpResponse response = httpClient.execute(request);
        //pega a resposta e lê em formato string
        HttpEntity responseEntity = response.getEntity();
        String json = responseToString(responseEntity);
        //converte de json para o objeto
        Usuario usuario = new Gson().fromJson(json, Usuario.class);
        Log.i("Usuario ",usuario.getNome());
        return usuario;

        }catch (Exception e){
            Log.e("GetUsuario",e.getMessage());
        }
        return null;
    }

    String responseToString(HttpEntity responseEntity) throws Exception
    {
        char[] buffer = new char[(int) responseEntity.getContentLength()];
        InputStream stream = responseEntity.getContent();
        InputStreamReader reader = new InputStreamReader(stream);
        reader.read(buffer);
        stream.close();
        return new String(buffer);
    }

    @Override
    protected String doInBackground(String... params) {
        String serverResponse = "";

        try {
            int requestType = Integer.parseInt(params[0]);

            switch (requestType){
                case 1:
                    getUsuario("1");
                    break;
               }
        } catch (Exception e) {
            serverResponse = e.getMessage();
        }
        return serverResponse;
    }
}
